Ext.ns('ru.proburo.oms.air.dao');

ru.proburo.oms.air.dao.TreeLoader = Ext.extend(Ext.tree.TreeLoader, {
	
	/**
	 * @cfg {Object} conn
	 * An {@link Ext.data.SQLiteDB} database connection instance
	 */
	/**
	 * @cfg {String} dbFile
	 * A database file to open, if conn is not set
	 */
	/**
	 * @cfg {String} query
	 * SQL query
	 */
	constructor: function(config)
	{
		config = config || {};
		
		if(!config.conn || config.dbFile)
		{
			config.conn = new Ext.data.SQLiteDB({dbFile: config.dbFile})
		}
		
		ru.proburo.oms.air.dao.TreeLoader.superclass.constructor.call(this, config);
	},
	
    load: function(node, callback, scope)
	{
        if(this.clearOnLoad)
		{
            while(node.firstChild)
			{
                node.removeChild(node.firstChild);
            }
        }
        if(this.doPreload(node))
		{
			// preloaded json children
            this.runCallback(callback, scope || node, [node]);
        }
		else if(this.conn && this.query)
		{
            this.requestData(node, callback, scope || node);
        }
    },
	
	requestData: function(node, callback, scope)
	{
		if(false !== this.fireEvent("beforeload", this, node, callback))
		{
			this.stmt = this.conn.queryBy(this.query, [node.attributes.id], function(type, success, result, stmt, db){
				
				if(!success)
				{
					this.handleFailure(result, node, callback, scope);
				}
				else
				{
					this.handleResponse(result, node, callback, scope);
				}
			}, this);
        }
		else
		{
            // if the load is cancelled, make sure we notify
            // the node that we are done
            this.runCallback(callback, scope || node, []);
        }
    },

    handleResponse: function(result, node, callback, scope)
	{
        this.stmt = false;
        this.processResponse(result, node, callback, scope);
        this.fireEvent("load", this, node, result);
    },

    processResponse: function(result, node, callback, scope)
	{
		try
		{
            node.beginUpdate();
			
            for(var i = 0, len = result.records.length; i < len; i++)
			{
				var n = this.createNode(result.records[i]);
				
                if(n)
				{
                    node.appendChild(n);
                }
			}
            node.endUpdate();
            this.runCallback(callback, scope || node, [node]);
        }
		catch(e)
		{
            this.handleFailure(result, node, callback, scope);
        }
    },

    handleFailure: function(result, node, callback, scope)
	{
		this.stmt = false;
		this.fireEvent("loadexception", this, node, result);
        this.runCallback(callback, scope || node, [node]);
    },

    abort: function()
	{
        if(this.isLoading())
		{
            this.stmt.cancel();
        }
    },

    isLoading: function()
	{
        return !!this.stmt;
    },

    destroy: function()
	{
        this.abort();
        this.purgeListeners();
    }
});